package gamehandler

import (
	"context"
	cfg "wanyu/server/api/gameapi/gamecfg"
	pb "wanyu/server/protogo/gamebase"
	dbg "wanyu/server/protogo/gamedebug"
	"wanyu/server/protogo/public"
	"wanyu/server/protogo/roomsrv"

	//cst "wanyu/server/engine/globaldef/consts"

	//log "wanyu/server/engine/wplog"

	"github.com/gogo/protobuf/proto"
	empty "github.com/golang/protobuf/ptypes/empty"
	//"github.com/micro/go-micro/broker"
	//"github.com/micro/go-micro/client"
)

type RpcSrv struct{}

func (*RpcSrv) RemovePlayer(ctx context.Context, req *pb.RemovePlayerReq, rsp *empty.Empty) error {
	roomMgr.LeaveRoom("roomsrv", req.PlayerID, req.Flag)
	return nil
}

func (*RpcSrv) UpdateGameCfg(ctx context.Context, req *roomsrv.RegGameSvrRsp, rsp *empty.Empty) error {
	cfg.SetRawCfg(req)
	return nil
}

func (*RpcSrv) AddStrategy(ctx context.Context, req *pb.AddStrategyReq, rsp *empty.Empty) error {
	roomMgr.SetStrategy(req.PlayerId, req.Strategy, req.KindID)
	return nil
}

func (*RpcSrv) DelStrategy(ctx context.Context, req *pb.DelStrategyReq, rsp *empty.Empty) error {
	roomMgr.DelStrategy(req.PlayerId, req.KindID)
	return nil
}

func (*RpcSrv) PrepareEnter(ctx context.Context, req *pb.PrepareEnter, rsp *empty.Empty) error {
	return roomMgr.PrepareEnter(req)
}

func (*RpcSrv) GetRoomList(ctx context.Context, req *empty.Empty, rsp *dbg.GetRoomListRsp) error {
	//rsp = roomMgr.GetRoomList()
	if ret := roomMgr.GetRoomList(); nil != ret {
		rsp.Agents = ret.Agents
	}
	return nil
}

func (*RpcSrv) GetPlayer(ctx context.Context, req *dbg.GetPlayerReq, rsp *dbg.Player) error {
	proto.Merge(rsp, roomMgr.GetPlayer(req))
	return nil
}

func (*RpcSrv) GetSummary(ctx context.Context, req *empty.Empty, rsp *dbg.GetSummaryRsp) error {
	proto.Merge(rsp, roomMgr.GetSummary())
	return nil
}

func (pb *RpcSrv) GeneralMessage(ctx context.Context, req *public.GeneralMessageRequest, rsp *public.GeneralMessageResponse) error {

	/*
	   此处需要各服务处理自身业务，在不影响业务的情况下
	   返回消息，等待关闭
	*/

	var err error

	switch req.Code {

	case public.PublicsType_PersonControl:

		message:=&public.PublicsPersonControl{}

		err= proto.Unmarshal(req.Message,message)

		roomMgr.SetPersonControl(message)
	}

	rsp = nil

	return err
}

//Publics 通用接口
type Publics struct{}

//GeneralMessage 通用消息
/*
收到消息后自行处理各自业务，确保数据无异常后返回消息
*/
func (pb *Publics) GeneralMessage(ctx context.Context, req *public.GeneralMessageRequest, rsp *public.GeneralMessageResponse) error {
	/*
	   此处需要各服务处理自身业务，在不影响业务的情况下
	   返回消息，等待关闭
	*/
	rsp = nil
	return nil
}
